package phonebook;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.andro.chansung.ConstantName;
import com.andro.chansung.DB;

import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class PhoneRetrevingDataThread extends Thread {
	private String url;
	private String title;
	private Activity activity;
	private Handler handler;
	
	public PhoneRetrevingDataThread(Activity activity, Handler handler, String url, String title) {
		this.url = url;
		this.title = title;
		this.activity = activity;
		this.handler = handler;
	}

	public void run() {
		try {
			Document doc = Jsoup.connect(url).data("name", title).get();
			Elements innerParties = doc.select("title_name");
			
			Log.d("hm...", doc.text());
			
			SQLiteDatabase db = activity.openOrCreateDatabase(ConstantName.DATABASE_NAME, Context.MODE_WORLD_WRITEABLE, null);
			for( Element element : innerParties ) {
				String name = element.attr("name");
				String phone = element.select("phone").get(0).text();
				
				Map<String, String> phoneNumbers = new HashMap<String, String>();
				
				if( phone.contains("-") ) {
					phone = phone.split("\n")[0].split(",")[0].split("~")[0];	
				} else {
					phone = "055-320-" +  phone.split("\n")[0].split(",")[0].split("~")[0];	
				}
				
				phoneNumbers.put(name, phone);
				
				Map<String, String> faxNumbers = new HashMap<String, String>();
				
				DB.insertDataIntoPhoneBookTable(db, new Phone(title, phoneNumbers, faxNumbers));
			}
			db.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Bundle bundle = new Bundle();
		bundle.putString("title", title);
		Message msg = new Message();
		msg.setData(bundle);
		
		handler.sendMessage(msg);
	}
}